package com.own.business.system.account.common.core;

import com.own.business.system.account.common.hook.AccountLogoutHook;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * AccountLogoutSpringHook
 *
 * @author chenxueli
 * @date 2023-08-04 13:45:57
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class AccountLogoutSpringHook implements ApplicationContextAware, ApplicationListener<ApplicationEvent> {

    private static final List<AccountLogoutHook> ACCOUNT_LOGOUT_HOOK_LIST = new ArrayList<>();
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        AccountLogoutSpringHook.applicationContext = context;
    }

    /**
     * 执行账号注销
     *
     * @param userId 用户id
     * @param reason 注销原因
     */
    public void run(Long userId, String reason) {
        ACCOUNT_LOGOUT_HOOK_LIST.forEach(service -> service.run(userId, reason));
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent) {
            applicationContext.getBeansOfType(AccountLogoutHook.class).forEach((key, service) -> {
                ACCOUNT_LOGOUT_HOOK_LIST.add(service);
                log.debug("账号注销执行器：【{}】", service.getClass().getName());
            });
        }
    }

}
